<?php
/**
 * 支付宝多商户支付
 * 2024/08/19
 * 弃用--->使用app\apiadmin\controller\user\User->getAlipay
 */

namespace app\apiadmin\controller\user;

use app\apiadmin\controller\liveManager\LiveStatus;
use app\apiadmin\service\liveManager\LiveManagerService;
use app\apiadmin\service\statics\LiveUserGetDataService;
use app\common\alipay\aop\AlipayTradeService;
use app\common\alipay\aop\AopClient;
use app\common\alipay\aop\request\AlipayTradeRefundRequest;
use app\common\alipay\aop\request\AlipayTradeWapPayRequest;
use app\common\controller\BaseController;
use app\common\utils\Res;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class Alipay extends BaseController
{
    /**
     * 获取支付宝支付
     * @return \think\response\Json
     * @author cc
     */
    public function getAlipay()
    {
        $param = $this->request->param();
        if (!isset($param['orderid']) || empty($param['orderid'])) {
            return Res::error('请先选择订单！');
        }
        $order_info = DB::table('xh_siyu_order')->where('id', $param['orderid'])->find();
        if (!$order_info) {
            return Res::error('订单不存在！');
        }
        $where = [];
        if (isset($order_info['seller_id']) && !empty($order_info['seller_id'])) {
            $where[] = ['account', '=', $order_info['seller_id']];
            $where[] = ['del', '=', 0];
        } else {
            $where[] = ['flag', '=', 2];
            $where[] = ['state', '=', 1];
            $where[] = ['del', '=', 0];
        }
        $merchantInfo = Db::table('xh_siyu_fuwushang_account')->where($where)->find();
        if (!$merchantInfo) {
            return Res::error('暂时没有激活的支付宝商户！');
        }

        // 沙箱测试
        //        $order_info = [
        //            'order_num' => '70501111111S001111119',
        //            'fee' => '9.9',
        //            'seller_id' => '2088721041849420',
        //        ];
        //        $config = [
        //            'app_id' => '9021000140613279',
        //            'alipay_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2eE9lBRN50GkugrQz1238gG6Ib/r/fTiKuNJ0BNoS63r7DOuF4wylBRN7bRQ6gtea8bYy8vidoIKwJBwDAFB6A822m3NORg/F7kjTse38A8AJawaineEDhK3S+kkHPtf+WG75Zpb90/MH7cvInrBMrhqU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Pbp5bdVbVaf/rDiPECgYEA2zEpHRi5Y9+Ik9FGwL0czPBVKQYSW2VbkYvrMkRV/1h7fldoiAZvoXoCQ8u0/cY9tMuDvLz1R7suVbZL4NhH5hpFhXDnVBT12ebpLWJFqmbNN9ZGLYuk49FGlTpuJYKuFMbyPfmCl7VguuFJr8O95V31EKabu2gwQtfM5xMMJE0CgYAXbx0iONrTzQqFiEDiQe0MKUlYDIoBGmycxZz3Iou7283I7cpPC0a+pPYSM96CiEHVNkois/awE2eHEUlzoezlmywHWwTTNd67NxdHu0rEBB2KjCJ7fzDwhRRagKR/WLG90TBF15HN7+vdgCaEiHD9McPG25t/rC8glT9bJR1T4QKBgDqktnlAailcXvAdZ66dah0yl7Y4F6U4Qv13z99NBS0iAThWLnNmNWugdwaoc64J4eyDHqXacE1WuRjZgwePFf1sPflrsZh/Wx+Hdg9cYYMrqfAsde4tlFoXXakDTwDeK7EHYTxPiy8Hqe+V4t8RobbCIpTn3naPc4oOrpWMNQ1pAoGAR1j8gC1NJOVPW0RwoIj7Tq6ydTjFYBuGPEAXIThvpDLFslwI+xMqMm/4u1tDF5llrCMHD99UEdrzaNV05B5EhQNYitEoy9oHHz+hOOCnIkbxPVqoEOodNr8ZXPgtbf3BvBOZEFJvR7urjE2LGBlhI6koKLWlJVC2hm5VLqXDfxA=',
        //            'notify_url' => 'https://liveapi.banxued.com/apiadmin/alipay/alipay_notify',
        //            'gatewayUrl' => "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
        //            'app_auth_token' => "202408BB7cc83a8b582a453584672c36aca08B73",
        //        ];

        $config = config('alipay');

        $alipayClient = new AopClient();
        $alipayClient->gatewayUrl = $config['gatewayUrl'];
        $alipayClient->appId = $config['app_id'];
        $alipayClient->rsaPrivateKey = $config['merchant_private_key'];
        $alipayClient->alipayrsaPublicKey = $config['alipay_public_key'];
        $alipayClient->signType = "RSA2";
        $alipayClient->postCharset = "UTF-8";
        $alipayClient->format = "JSON";
        $alipayClient->apiVersion = "1.0";

        $info = [
            'out_trade_no' => $order_info['order_num'],
            'total_amount' => $order_info['fee'] / 100,
            'subject' => DB::table('xh_siyu_course')->where('id', $order_info['courseid'])->column('name'),
            'product_code' => 'QUICK_WAP_WAY',
            'seller_id' => !empty($order_info['seller_id']) ? $order_info['seller_id'] : $merchantInfo['account'],
        ];
        $request = new AlipayTradeWapPayRequest();
        $request->setBizContent(json_encode($info));
        $request->setNotifyUrl($config['notify_url']);
        $pageRedirectionData = $alipayClient->pageExecute($request, "POST", $merchantInfo['sp_appid']);
        // 如果需要返回GET请求，请使用
        //         $pageRedirectionData = $alipayClient->pageExecute($request, "GET");
        return Res::ok($pageRedirectionData);

    }

    /**
     * 支付宝支付回调
     * @return void
     * @author cc
     */
    public function alipay_notify()
    {
        $d['remark'] = "支付宝支付成功后回调地址111111111111";
        Db::table('xh_siyu_user_remark')->save($d);

        $param = $this->request->param();
        if (isset($param)) {
            $d1['remark'] = "支付宝支付成功以后给回调的数据" . json_encode($param);
            DB::table('xh_siyu_user_remark')->save($d1);
        }
        $config = config('alipay');
        $configInfo = [
            'app_id' => $config['app_id'],
            'merchant_private_key' => $config['merchant_private_key'],
            'notify_url' => $config['notify_url'],
            'return_url' => $config['return_url'],
            'charset' => "UTF-8",
            'sign_type' => "RSA2",
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            'alipay_public_key' => $config['alipay_public_key'],
            'log_path' => "",
        ];
        $alipaySevice = new AlipayTradeService($configInfo);
        $alipaySevice->writeLog(var_export($param, true));
        $check = $alipaySevice->check($param);

        if (isset($check)) {
            $d1['remark'] = "我是支付宝支付回调验签的的结果check=" . $check;
            DB::table('xh_siyu_user_remark')->save($d1);
        }
        if ($check) {
            $oo = Db::name('siyu_order')->where(['order_num' => $param['out_trade_no']])->find();
            if ($oo && $param['trade_status'] == 'TRADE_SUCCESS' && $oo['state'] == 0) {
                echo 'success';
                //我这里设置的是，如果返回值是支付成功，那么就把这个订单状态给改状态
                //out_trade_no这个是返回的订单号

                // 获取公域订单
                $unionId = Db::table('xh_siyu_user_order_zhujiao_log')->where(['live_id' => $oo['liveId'], 'user_id' => $oo['user_id']])->value('xh_order_union_id');
                $orderId = LiveManagerService::checkXhOrder($unionId);

                $data['state'] = 1;
                $data['trade_no'] = $param['trade_no'];
                $data['pay_time'] = $param['gmt_payment'];
                $data['trade_state_desc'] = '支付成功';
                $data['order_id'] = !empty($orderId) ? $orderId : 0;
                $data['seller_id'] = $param['seller_id'];
                Db::name('siyu_order')->where(['order_num' => $param['out_trade_no']])->save($data);
                //删除改价key
                if ($oo['key']) {
                    $redis = \app\apiadmin\service\data\RedisService::makeService();
                    $redis->del($oo['key']);
                }
                //关联定金
                if ($oo['deposit_ids']) {
                    $deposit_ids = explode(',', $oo['deposit_ids']);
                    if ($deposit_ids) {
                        foreach ($deposit_ids as $id) {
                            $data = [
                                'siyu_order_id' => $oo['id'],
                            ];
                            DB::table('xh_siyu_deposit')->where(array('id' => $id))->save($data);
                        }
                    }
                }

                $o = Db::name('siyu_order')->where(['order_num' => $param['out_trade_no']])->find();

                //打日志，做记录
                $m = [];
                $m['liveId'] = $o['liveId'];
                $m['live_user_id'] = $o['user_id'];
                $s = db::table('xh_siyu_invitation_user_signin')->where($m)->find();
                if ($s) {
                    $a = [];
                    $a['chengjiao'] = 3;
                    $a['chengjiao_time'] = date('Y-m-d H:i:s');
                    $a['order_num'] = $o['order_num'];
                    db::table('xh_siyu_invitation_user_signin')->where($m)->save($a);
                } else {
                    $a = [];
                    $a['liveId'] = $o['liveId'];
                    $a['live_user_id'] = $o['user_id'];
                    $a['order_num'] = $o['order_num'];
                    $a['chengjiao'] = 3;
                    $a['chengjiao_time'] = date('Y-m-d H:i:s');
                    db::table('xh_siyu_invitation_user_signin')->insertGetId($a);
                }

                //统计提单数据
                $liveId = $o['liveId'];
                $liveStatus = new LiveStatus($o['liveId']);
                $liveStatus->set_xiaoshoue_yifukuan(intval($o['fee']));
                $liveStatus->set_xiadan_danshu_yifukuan($o['order_num']);
                $liveStatus->set_xiadan_rensu_yifukuan($o['user_id']);

                $liveStatus->remove_xiaoshoue_weifukuan(intval($o['fee']));
                $liveStatus->remove_xiadan_danshu_weifukuan($o['order_num']);
                $liveStatus->remove_xiadan_renshu_weifukuan($o['user_id']);

                //行为记录添加数据详情
                $collection = 'live_event';
                $liveOrder = new LiveUserGetDataService($collection);

                $map = [];
                $map['user_id'] = $o['user_id'] . '';
                $map['liveId'] = $liveId;

                $update = ['$set' => ['event' => '下单']];
                $r = $liveOrder->updateEvent($map, $update);

                // 新增/修改 公域订单状态
                if (!empty($orderId)) {
                    $session = Db::table('xh_siyu_live_manager')->where('id', $liveId)->value('venue');
                    LiveManagerService::getLiveOrderState($liveId, $session, $orderId, 3, $o['wx_unionid'], $o['tutorId'], $o['id'], $o['fee']);
                }

                echo 'success';
            }
            //定金
            $dd = Db::name('siyu_deposit')->where(['deposit_num' => $param['out_trade_no']])->find();
            if ($dd && $param['trade_status'] == 'TRADE_SUCCESS' && $dd['state'] == 0) {
                // echo 'success';

                $data['state'] = 1;
                $data['trade_no'] = $param['trade_no'];
                $data['pay_time'] = $param['gmt_payment'];
                $data['actual_payment_fee'] = $dd['fee'];
                $data['trade_state_desc'] = '支付成功';
                Db::name('siyu_deposit')->where(['deposit_num' => $param['out_trade_no']])->save($data);

                echo 'success';
            }

        }

    }

    /**
     * 支付宝退款
     * @param $trade_no
     * @param $refund_amount
     * @param $out_trade_no
     * @param $out_request_no
     * @param $part_type
     * @return \think\response\Json
     * @throws \Exception
     * @author cc
     */
    public static function alipay_refund($trade_no, $refund_amount, $out_trade_no, $out_request_no, $part_type)
    {
        $order_info = DB::table('xh_siyu_order')->where('trade_no', $trade_no)->find();
        if (!$order_info) {
            return Res::error('订单不存在！');
        }
        $where = [];
        if (isset($order_info['seller_id']) && !empty($order_info['seller_id'])) {
            $where[] = ['account', '=', $order_info['seller_id']];
            $where[] = ['del', '=', 0];
        } else {
            $where[] = ['flag', '=', 2];
            $where[] = ['state', '=', 1];
            $where[] = ['del', '=', 0];
        }
        $merchantToken = Db::table('xh_siyu_fuwushang_account')->where($where)->value('sp_appid');

        $config = config('alipay');
        $alipayClient = new AopClient();
        $alipayClient->gatewayUrl = $config['gatewayUrl'];
        $alipayClient->appId = $config['app_id'];
        $alipayClient->rsaPrivateKey = $config['merchant_private_key'];
        $alipayClient->alipayrsaPublicKey = $config['alipay_public_key'];
        $alipayClient->signType = "RSA2";
        $alipayClient->postCharset = "UTF-8";
        $alipayClient->format = "JSON";
        $alipayClient->apiVersion = "1.0";
        $refund_amount = $refund_amount / 100;
        $info = [
            'out_trade_no' => $out_trade_no,
            'refund_amount' => $refund_amount,
            'trade_no' => $trade_no,
            'out_request_no' => $out_request_no,
        ];
        $request = new AlipayTradeRefundRequest();
        try {
            $request->setBizContent(json_encode($info));
            $responseResult = $alipayClient->execute($request, null, $merchantToken);
            $responseApiName = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $response = $responseResult->$responseApiName;
            if (empty($response->code) || $response->code != 10000) {
                Log::info('支付宝退款接口返回数据-' . serialize($response));
                throw new Exception('退款接口调用失败:' . serialize($response), 1);
            }
            $data['code'] = 0;
            $data['message'] = '退款成功';
            $data['result'] = json_encode($response);
            if (in_array($part_type, [0, 1])) {
                $o = Db::name('siyu_order')->where(['trade_no' => $trade_no])->find();
                //统计提单数据
                $liveId = $o['liveId']; //透传参数  直播ID
                $liveStatus = new LiveStatus($liveId);
                $liveStatus->set_xiaoshoue_tuikuan($o['fee']);
                $liveStatus->set_xiadan_danshu_tuikuan($o['order_num']);
                $liveStatus->set_xiadan_renshu_tuikuan($o['user_id']);
            }
            return $data;

        } catch (Exception $e) {
            // 捕获异常并执行相应的代码
            Log::info('支付宝退款接口异常数据-' . $e->getMessage());
            $data['code'] = $e->getCode();
            $data['message'] = $e->getMessage();
            return $data;
        }
    }

}
